package groupb6.shopsystem.messaging.group;

import groupb6.shopsystem.messaging.BeanFactory;
import groupb6.shopsystem.util.JWTUtil;
import groupb6.shopsystem.util.response.ResponseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;

;

/*
 * Websocket抽象服务器
 * 接受前端发起的wb请求
 * @Author zhangyn
 * */
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/group")
public class WSGroupEndpoint {

        //此对象需要手动注入bean
        private WSGroupService WSGroupService;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        sessionParamsVerify(session);
        WSGroupService = new BeanFactory().getApplicationContext().getBean(WSGroupService.class);
        WSGroupService.open(session);

    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        sessionParamsVerify(session);
        WSGroupService = new BeanFactory().getApplicationContext().getBean(WSGroupService.class);
        WSGroupService.close(session);

    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable exception) {
        WSGroupService.error(session,exception);
        //TODO:处理连接错误时逻辑

    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        sessionParamsVerify(session);
        WSGroupService = new BeanFactory().getApplicationContext().getBean(WSGroupService.class);
        WSGroupService.message(session,message);

    }

    private void sessionParamsVerify(Session session){
        Integer customerId;
        Integer sellerId;
        String token;
        try {
            Map<String, List<String>> queryParams = session.getRequestParameterMap();
            customerId = Integer.parseInt(queryParams.get("customerId").get(0));
            sellerId = Integer.parseInt(queryParams.get("sellerId").get(0));
            token=queryParams.get("token").get(0);
        } catch (NullPointerException e) {
            throw new NullPointerException("url请求方式错误:字段不完整");
        }
        try{
            JWTUtil.getCurrentUserWS(session);
        }catch (ResponseException e){
            throw new RuntimeException("token认证错误");

        }
    }
}
